package com.example.login.Controller;

import com.example.login.Pojo.Address;
import com.example.login.Pojo.User;
import com.example.login.Service.AddressService;
import com.example.login.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;

@Controller
public class InformationController {
    @Autowired
    AddressService addressService;
    public String add(@ModelAttribute("address")Address address){
       addressService.addAddress(address.getUser_id(),address.getUser_name(),address.getTel(),
               address.getProvince(),address.getCity(),address.getCounty(),address.getAll_address(),
               address.getAddress_tag());
        return "";
    }

    @RequestMapping("/user/information")
    public String infor(HttpSession session, Model model)
    {
        User user =(User)session.getAttribute("user");
        int user_id =user.getId();

        ArrayList<Address> addressList = addressService.getAddress(user_id);
        System.out.println(addressList);
        Address address =new Address();
        model.addAttribute("address",address);
        model.addAttribute("addressList",addressList);
        model.addAttribute("user",user);
        return "/商家中心/地址管理";
    }

    //修改用户个人资料
    @Autowired
    UserService userService;
    @RequestMapping("/user/change")
    public String change(@ModelAttribute("user") User user,HttpSession session)
    {
        User u=(User)session.getAttribute("user");
        int id =u.getId();
        String userName=user.getUsername();
        userService.updateName(userName,id);
        u.setUsername(userName);
        session.setAttribute("user",u);
        return "redirect:/user/information";
    }

    @RequestMapping("/user/address")
    public String address(@ModelAttribute("address") Address address,HttpSession session)
    {
        User user=(User) session.getAttribute("user");
        System.out.println(address);
        //添加地址
        addressService.addAddress(user.getId(),address.getUser_name(),address.getTel(),
                address.getProvince(),address.getCity(),address.getCounty(),address.getAll_address(),
                address.getAddress_tag());
        return"redirect:/user/information";
    }
    @RequestMapping("/user/address/{address_id}")
    public String address(@PathVariable("address_id") int address_id,HttpSession session)
    {
        User user=(User) session.getAttribute("user");
        int user_id=user.getId();
        addressService.update(user_id);
        addressService.updateTag(user_id,address_id);
        return "redirect:/user/information";
    }
}
